package com.hsy.swu.widget

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.View
import android.widget.RemoteViews
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.google.gson.Gson
import com.hsy.swu.R
import com.hsy.swu.home.course.CourseModel
import com.hsy.swu.home.course.SimpleCourseModel
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.hsyutils.fileWrite
import com.hsy.swu.login.LoginActivity
import java.time.Duration
import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun Context.pinCourseWidget() {
    val mAppWidgetManager = getSystemService(AppWidgetManager::class.java)
    val componentName = ComponentName(this, CourseWidget::class.java)

    val appWidgetIds = mAppWidgetManager.getAppWidgetIds(componentName)
    if (appWidgetIds.isEmpty()) {
        if (mAppWidgetManager.isRequestPinAppWidgetSupported) {
            mAppWidgetManager.requestPinAppWidget(componentName, null, null)
        } else {
            MActivityUtil.showToast("设备 SDK版本不支持组件功能")
        }
    } else {
        MActivityUtil.showToast("课程提醒组件已添加")
    }
}

fun Context.updateCourseWidget(list: List<SimpleCourseModel>) {
    val mAppWidgetManager = getSystemService(AppWidgetManager::class.java)
    val componentName = ComponentName(this, CourseWidget::class.java)
    val remoteView = RemoteViews(packageName, R.layout.widget_course)

    val remoteViewList = listOf(
        Triple(R.id.linearLayout1, R.id.tvName1, R.id.tvInfo1),
        Triple(R.id.linearLayout2, R.id.tvName2, R.id.tvInfo2),
        Triple(R.id.linearLayout3, R.id.tvName3, R.id.tvInfo3),
        Triple(R.id.linearLayout4, R.id.tvName4, R.id.tvInfo4),
        Triple(R.id.linearLayout5, R.id.tvName5, R.id.tvInfo5),
        Triple(R.id.linearLayout6, R.id.tvName6, R.id.tvInfo6)
    )
    for (showIndex in list.indices) {
        val courseModel = list[showIndex]
        remoteView.setTextViewText(remoteViewList[showIndex].second, courseModel.courseName)
        remoteView.setTextViewText(
            remoteViewList[showIndex].third,
            "${courseModel.classRoom} | ${courseModel.time}"
        )
        remoteView.setViewVisibility(remoteViewList[showIndex].first, View.VISIBLE)
    }
    for (goneIndex in list.size..5) {
        remoteView.setViewVisibility(remoteViewList[goneIndex].first, View.GONE)
    }

    mAppWidgetManager.updateAppWidget(componentName, remoteView)
}

fun Context.updateSimpleCourseModelFile(courseList: List<CourseModel>) {
    val jsonStr = Gson().toJson(SimpleCourseModel.toSimpleCourseModelList(courseList))
    fileWrite(jsonStr, "simpleCourseModelList.json")
}

fun Context.postCourseNotification(simpleCourseModel: SimpleCourseModel) {
    val mChannelId = "mChannelId"
    val mNotificationId = 0

    val notificationChannel = NotificationChannel(
        mChannelId,
        getString(R.string.app_name),
        NotificationManager.IMPORTANCE_HIGH
    )
    val mManager: NotificationManager =
        getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
    mManager.createNotificationChannel(notificationChannel)

    val mNotification = NotificationCompat.Builder(this, mChannelId).apply {
        val startTimeString = simpleCourseModel.time.split("-")[0]
        val startTime = LocalTime.parse(startTimeString, DateTimeFormatter.ofPattern("HH:mm"))
        val remainMinutes = Duration.between(LocalTime.now(), startTime).toMinutes() + 1
        setContentTitle("距下节课还有 $remainMinutes 分钟")
        setContentText("${simpleCourseModel.courseName}\n${simpleCourseModel.classRoom} | ${simpleCourseModel.time}")
        setSmallIcon(R.drawable.launcher)
        setAutoCancel(true)
        setCategory(NotificationCompat.CATEGORY_EVENT)
        setContentIntent(
            PendingIntent.getActivity(
                this@postCourseNotification,
                0,
                Intent(this@postCourseNotification, LoginActivity::class.java),
                PendingIntent.FLAG_MUTABLE
            )
        )
    }.build()
    mManager.notify(mNotificationId, mNotification)
}

fun Context.goToSystemPermissionSetting() {
    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    intent.data = Uri.parse("package:$packageName")
    startActivity(intent)
}